import { useFrame, useLoader } from "@react-three/fiber";
import { useRef } from "react";
import { Color, MathUtils, Mesh } from "three";
import { TextureLoader } from "three/src/loaders/TextureLoader";

export default function Earth() {
  const obj = useRef<any>();
  const cloud = useRef<any>();
  const colorMap = useLoader(TextureLoader, "earth.jpg");
  const cloudMap = useLoader(TextureLoader, "cloud.jpg");
  useFrame(({ clock }) => {
    const target = obj.current as Mesh;
    const time = clock.elapsedTime;
    target.rotation.x = Math.PI * 0.3 + time * 0.25;
    cloud.current.rotation.x = Math.PI * time * 0.005;
  });
  return (
    <group
      ref={obj}
      position={[0, 0, -850]}
      rotation={[Math.PI * 0.3, MathUtils.degToRad(45), Math.PI / 3]}
    >
      <mesh>
        <sphereBufferGeometry args={[638, 128, 128]}></sphereBufferGeometry>
        <meshStandardMaterial map={colorMap}></meshStandardMaterial>
      </mesh>
      <mesh ref={cloud}>
        <sphereBufferGeometry args={[640, 128, 128]}></sphereBufferGeometry>
        <meshStandardMaterial
          color={0xffffff}
          map={cloudMap}
          transparent
          opacity={0.35}
        ></meshStandardMaterial>
      </mesh>
      <mesh>
        <sphereBufferGeometry args={[642, 128, 128]}></sphereBufferGeometry>
        <meshStandardMaterial
          color={0x7bd3dc}
          transparent
          opacity={0.25}
        ></meshStandardMaterial>
      </mesh>
      <fog color={new Color(0x000000)} near={100} far={700} />
      <directionalLight
        args={[0xffffff, 0.375]}
        position={[1800, 100, 0]}
      ></directionalLight>
      <mesh position={[1800, 100, 0]}>
        <sphereBufferGeometry args={[15, 32, 32]}></sphereBufferGeometry>
        <meshBasicMaterial color={0xffffff}></meshBasicMaterial>
      </mesh>
    </group>
  );
}
